/*
 * SpeedoDyno - Speedometer and dynamometer application for Android 
 * Copyright 2013 Guilhem VALENTIN
 * 
 * This file is part of SpeedoDyno
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with SpeedoDyno. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gvalentin.speedodyno.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.os.Environment;
import android.util.Log;

/**
 * Utility methods to manipulate files
 * @author guilhem
 */
public class FileUtil {
	
	private static final String TAG = FileUtil.class.getSimpleName();

	private static final SimpleDateFormat dfymd = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
	
	/**
	 * Get the name of the file where to store 
	 */
	public static File getCsvLogFile(String prefix) {
		String fileSuffix = dfymd.format(new Date());
		String filename = Environment.getExternalStorageDirectory().getPath()+"/SpeedoDyno/"+prefix+"_"+fileSuffix+".csv";

		return new File(filename);
	}
	
	/**
	 * Write buffer to file
	 */
	public static void writeCsvToFile(File file, CharSequence buffer) {
		FileOutputStream fOut = null;
		OutputStreamWriter fOutWriter = null;
		try {
			file.getParentFile().mkdirs();
			if (!file.exists()) {
				file.createNewFile();
			}
			fOut = new FileOutputStream(file, true);
			fOutWriter = new OutputStreamWriter(fOut);
			fOutWriter.append(buffer);
			Log.d(TAG, "Done writing file '" + file.getPath() + "'");
		} catch (Exception e) {
			Log.e(TAG, "Error writing file '" + file.getPath() + "': " + e, e);
		} finally {
			if (fOutWriter != null) {
				try { fOutWriter.close(); } catch (IOException e) {}
			}
			if (fOut != null) {
				try { fOut.close(); } catch (IOException e) {}
			}
		}
	}
}
